
$(function(){

    // var _inviter = '';
    // var url = location.search; //获取url中"?"符后的字串  

    // var theRequest = new Object();  
    // if (url.indexOf("?") != -1) {  
    //     var str = url.substr(1);  
    //     strs = str.split("&");  
    //     for(var i = 0; i < strs.length; i ++) {  
    //        theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);  
    //     }  
    //     _inviter = theRequest.inviter != null?theRequest.inviter:'';
    //     // _target = theRequest.target != null?theRequest.target:'';
    // } 
    var scroll;
    var pageNum = 1;
    var _isImage = null,_isAdditional = null;

    var a_url = window.location.href;
    var a_title = '';
    var a_desc = '';
    var a_img = '';
    var a_summary = '火匣网';
    var _inviter = $.getUrlParam("inviter");
    var _index = $.getUrlParam("productid");
    var shareId = $.getUrlParam("share");
    var equipmentType = "common";
    // var mySwiper = new Swiper ('.info .swiper-container', {
    //     pagination: '.swiper-pagination',
    //     paginationElement : 'span',
    //     loop: true,//循环
    //     autoplay: 3000//播放间隔
    // });
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        equipmentType= "ios";
    } else if (/(Android)/i.test(navigator.userAgent)) {
        equipmentType = "android";
    } else {
        equipmentType = "common";
    }
    // 点击产品参数
    $(".product-data").on("click",function(){
        $(".gray").removeClass("tab");
        $('body').css('overflow-y','hidden')
    })
    $(".data-alert>input[type='button'],.gray").on("click",function(){
        $(".gray").addClass("tab");
        $('body').css('overflow-y','scroll')
    })
    //点击切换评论类型
    $(".comment-type>li").on("click",function(){
        $(this).addClass("active").siblings().removeClass("active");
    })
    
    //返回上一级
    $(".go-back").click(function(){
        go(decodeURIComponent(getCookie("productdetailgoback")));
    });
    //头部吸顶效果
    
    function navChangeColor(){
        $(".head-change li").on("click",function(){
            $(this).addClass("active").siblings().removeClass("active");
        }) 
    }
    // $('.all').click(function(){location.href = "#comment"})
    scrollNav();
    function scrollNav(){
        $(window).scroll(function() {
            scroll = $("body").scrollTop() || $(document).scrollTop();
            if(scroll >= 120){
                $(".head-change").stop().animate({"opacity":1},60);
                navChangeColor();
            }else{
                $(".head-change").stop().animate({"opacity":0},60);
            }
        });
        $('.h-goods').click(function(){
            $("html,body").animate({scrollTop:0}, 500)
        });
        $('.h-detail').click(function(){
            $('.comment').addClass('tab');
            $('.goods-detail,.share_use').removeClass('tab')
            location.href = "#product-data"
        })
       

    }
    //商品详情
    productDetail();
    function productDetail(){
        post({
            url:'/customizeProduct/'+_index+'/productDetail',
            success:function(data){
                console.log(data);
                var proPic = data.pictures;
                if(proPic){
                    for(var h in proPic){
                        $('.swiper-wrapper').append('<div class="swiper-slide"><img src="'+SERVER_CONTEXT_PATH+"/load/picture/"+proPic[h]+'"></div>')
                    }
                }
                if(proPic.length>1){
                    var mySwiper = new Swiper ('.info .swiper-container', {
                        pagination: '.swiper-pagination',
                        paginationElement : 'span',
                        loop: true,//循环
                        autoplay: 5000//播放间隔
                    });
                };
                if(data.productStatus == 'SALE_LOWER'){
                    $('.sale_down').removeClass('tab');
                    $('.now-design,.normal-buy').addClass('tab')
                }
                $('.keywords').html(data.keywords);
                $('.name').html(data.name);
                $('.minPrice').html(data.minPrice);
                $('.soldTotal').html(data.soldTotal);
                $('.reviewsTotal').html(data.reviewsTotal);
                $('.voteTotal').html(data.voteTotal);
                $('.manufacturer').html(data.manufacturer);
                $('.period').html(data.period);
                $('.remark').html(data.remark);
                $('.mfImageUrl').attr('src',''+SERVER_CONTEXT_PATH+"/load/picture/"+data.mfImageUrl+'');
                $("head").append('<meta name="keywords" content="'+data.keywords+'"/><meta name="description" content="'+data.keywords+'"/>');
                a_title = data.name;
                a_img = "https://"+window.location.host+"/load/picture/"+data.pictures[0];
                a_summary = data.keywords;
                $('.producer').click(function(){
                    go('/customize/designProduct/producter.html?producterId='+data.mfId)
                })

            },
            error:function(msg){
                console.log(msg)
            }
        })
    }
    // 产品参数
    attribute();
    function attribute(){
        post({
            url:'/customizeProduct/attribute/'+_index+'',
            success:function(data){
                console.log(data);
                for(var i in data){
                    $('.attribute').append('<li class="single">'+data[i].name+'：<i>'+data[i].optionalValue+'</i></li>')
                }
            },
            error:function(msg){
                console.log(msg)
            }
        })
    }
    // 下一步
    goNext();
    function goNext(){
        $('.now-design').click(function(){
            localStorage.setItem('selectdesign_goBackUrl',window.location.href)  //存当前url
            post({
                url:'/isLogin',
                success:function(data){
                    if(data){
                        go('/customize/gocustomize/selectDesign.html?productid='+_index+'&designType=DESIGN');
                    }else{
                        go('/login/index.html');
                    }
                }
            })
            
        });
        $('.normal-buy').click(function(){
            localStorage.setItem('selectdesign_goBackUrl',window.location.href)
            post({
                url:'/isLogin',
                success:function(data){
                    if(data){
                        go('/customize/gocustomize/selectDesign.html?productid='+_index+'&designType=ORIGINAL')
                    }else{
                        go('/login/index.html');
                    }
                }
            })
        })
    }
   
   
    function commentList(pageNum){
        //console.log(_isImage,_isAdditional)

        post({
            url:'/customizeProduct/reviewsPage',
            data:{
                page:pageNum,
                rows:5,
                productId:_index,
                type:'manufacturer',
                isImage:_isImage,
                isAdditional:_isAdditional,
            },
            success:function(data){
                console.log(data);
                // $('.commentlist').html('');
                var lists = data.reviewsList;
                if(lists.length){
                    $('.no-comment').addClass('tab')
                    $('.commentlist').removeClass('tab')
                    var _html = '';
                    for(var i in lists){
                        
                        var img_url = lists[i].avatar?SERVER_CONTEXT_PATH+'/load/picture/'+lists[i].avatar:"/common/img/avatar_default.jpg"
                        var _grade = lists[i].grade;
                        _html += '<div class="goods-comment">'
                        _html += '<div class="g-user clear"><img src="'+img_url+'" alt="">'
                        _html += '<span class="phone">'+lists[i].phone+'</span>'
                        if(_grade == 1){
                            _html += '<div class="star right"><ul class="grade clear"><li><img src="img/star.png" alt=""></li><li><img src="img/star1.png" alt=""></li><li><img src="img/star1.png" alt=""></li><li><img src="img/star1.png" alt=""></li><li><img src="img/star1.png" alt=""></li></ul></div>'
                        }else if(_grade == 2){
                            _html += '<div class="star right"><ul class="grade clear"><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star1.png" alt=""></li><li><img src="img/star1.png" alt=""></li><li><img src="img/star1.png" alt=""></li></ul></div>'
                        }else if(_grade == 3){
                            _html += '<div class="star right"><ul class="grade clear"><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star1.png" alt=""></li><li><img src="img/star1.png" alt=""></li></ul></div>'
                        }else if(_grade == 4){
                            _html += '<div class="star right"><ul class="grade clear"><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star1.png" alt=""></li></ul></div>'
                        }else if(_grade == 5){
                            _html += '<div class="star right"><ul class="grade clear"><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li><li><img src="img/star.png" alt=""></li></ul></div>'
                        }
                        _html +='</div>'
                        _html += '<div class="year-praise clear">'
                        _html += '<span class="left">'+getLocalTime(lists[i].createTime)+'</span>'
                        _html += '<b class="right"><img class="zan" src="img/zan.png" alt="">点赞</b></div>'
                        _html += '<p>'+lists[i].description+'</p>'
                        // _html += '<div class="comment-detail">'+lists[i].description+'</div>'
                        if(lists[i].imageUrl){
                            var _img = lists[i].imageUrl.split(',');
                            _html += '<div class="comment-img clear">'
                            console.log(lists[i].imageUrl)
                            for(var k in _img){
                                _html += '<img class="img_com" data-img="'+_img[k]+'" src="'+SERVER_CONTEXT_PATH+'/load/picture/'+_img[k]+'" alt="">'
                            }
                            _html += '</div>'
                        }
                        if(lists[i].additionalTime){
                            // var add_day = lists[i].additionalDay>0?lists[i].additionalDay+"天后":"当天"
                            _html += '<div class="again-comment">'
                            _html += '<div class="year-again clear"><span class="left">'+getLocalTime(lists[i].additionalTime)+'</span><i class="right" style="margin-right:0.14rem">追评</i></div>'
                            _html += '<p>'+lists[i].additionalDescription+'</p>'
                            if(lists[i].additionalImageUrl){
                                var img_add = lists[i].additionalImageUrl.split(',');
                                _html += '<div class="comment-img clear">'
                                for(var j in img_add){
                                    _html += '<img class="img_com" data-img="'+img_add[j]+'" src="'+SERVER_CONTEXT_PATH+'/load/picture/'+img_add[j]+'" alt="">'
                                }
                                _html += '</div>'
                            }
                            _html += '</div>'
                        }
                        _html +='</div>'
                    }
                    if(pageNum ==1){
                        $('.commentlist').html(_html)
                    }else{
                        $('.commentlist').append(_html)
                    }
                    
                }else if(data.total == 0){
                        $('.commentlist').addClass('tab')
                        $('.no-comment').removeClass('tab');
                }else{
                    $('.no-comment').addClass('tab');
                    $('.commentlist').removeClass('tab');
                }
                $('.condition li:nth-child(1)').click(function(){location.href = "#comments"})
            },
            error:function(msg){
                console.log(msg)
            }

        })
    }
    //筛选评论
     $('.h-comment').click(function(){
            $('.goods-detail,.share_use').addClass('tab');
            $('.comment').removeClass('tab');
            $('.commentlist').empty();
            pageNum =1
            location.href = "#comments";
            commentList(pageNum);
            
            

            

            
        })
     condition();iScroll();
    function condition(){
        $('.condition li').click(function(){
            $(this).addClass('active').siblings().removeClass('active');
            location.href = "#comments";
            $('.commentlist').empty();
        })

        $('.condition li:nth-child(1)').click(function(){
            _isImage = null;
            _isAdditional = null;
            pageNum = 1;
            commentList(pageNum);
            // location.href = "#comments";
        });
        $('.condition li:nth-child(2)').click(function(){
            _isImage = 1;
            _isAdditional = null;
            pageNum = 1;
            commentList(pageNum);
            // location.href = "#comments";
        });
        $('.condition li:nth-child(3)').click(function(){
            _isImage = null;
            _isAdditional = 1;
            pageNum = 1;
            commentList(pageNum);
            // location.href = "#comments";
        });
    }
    //评论图片放大
    // var imgs = [];
    
    // imglist();
    // function imglist(){

    //         $('.commentlist').delegate('.img_com','click',function(){
    //             var imgs = [$(this).data('img')]
    //             zoomImg($('.img_com'),imgs)
    //             // $('.img_com').each(function(){
    //             //     imgs.push($(this).data('img'));
    //             //     zoomImg($('.img_com'),imgs)
    //             // });console.log(imgs)
                
    //         })
    // }
    // 上拉刷新函数
    function iScroll() {
        function iScrollA() {
            var scrollTop = 0,
                bodyScrollTop = 0,
                documentScrollTop = 0;
            if (document.body) {
                bodyScrollTop = document.body.scrollTop;
            }
            if (document.documentElement) {
                documentScrollTop = document.documentElement.scrollTop;
            }
            scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
            return scrollTop;
        }

        function iScrollB() {
            var windowHeight = 0;
            if (document.compatMode == "CSS1Compat") {
                windowHeight = document.documentElement.clientHeight;
            } else {
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        }

        function iScrollC() {
            var scrollHeight = 0,
                bodyScrollHeight = 0,
                documentScrollHeight = 0;
            if (document.body) {
                bodyScrollHeight = document.body.scrollHeight;
            }
            if (document.documentElement) {
                documentScrollHeight = document.documentElement.scrollHeight;
            }
            scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
            return scrollHeight;
        }
        window.onscroll = function () {
            showGoTop($('body').scrollTop())
            if (iScrollC() == iScrollB() + iScrollA()) {
                pageNum += 1;
                commentList(pageNum);
                return pageNum;
            }
        }
    };
    // 时间轴处理
    function getLocalTime(nS) {     
        Date.prototype.toLocaleString = function() {
          return this.getFullYear() + "." + (this.getMonth() + 1) + "." + this.getDate();
        };
       return new Date(parseInt(nS)).toLocaleString();      
    } 


    //点击分享
    if(_inviter){
        post({
            url:'/isLogin',
            success:function(data){
                if(data){
                    $('.qr_code').addClass('tab');
                    $('.qr_code_2').removeClass('tab')
                }else{
                    $('.qr_code').removeClass('tab');
                    $('.qr_code_2').addClass('tab');
                    useInfo(_inviter);
                    $('.img_2').click(function(){
                        go('/register/index.html?inviter='+_inviter)
                    });
                }
            }
        })
        
       
    }else{
        $('.qr_code').addClass('tab');
        $('.qr_code_2').removeClass('tab')
    }
    
    function useInfo(id){
        
        post({
            url:'/invitee/info/'+id,
            success:function(data){
                console.log(data);
                if(data.avatar){
                    $('.img_1').attr('src',''+SERVER_CONTEXT_PATH +'/load/picture/'+data.avatar+'');
  
                }
                $('.name_fx').html("“"+data.phone+"”")
            }
        })
    }

    $(".share,.img_3").click(function(){
        // console.log(a_img,a_title,a_summary)
        $('body').css('overflow-y','hidden')
        if(equipmentType == "ios"){
            try{
                var message = {
                    'url' : window.location.href,
                    'title' : '火匣定制',
                    'Imageurl' : a_img,
                    'text' : a_title
                };
                window.webkit.messageHandlers.share.postMessage(message);
                //share(window.location.href,'火匣定制',a_img,a_title);
            }catch (e){
                if(isWeiXin() == false){
                    $(".wrap_share,.share_cover").removeClass("tab");
                }else{
                    $(".share_cover,.pay_container").removeClass("tab");
                }
            }
        }else if(equipmentType == "android"){
            try{
                contact.share(window.location.href,'火匣定制',a_img,a_title);
            }catch (e){
                if(isWeiXin() == false){
                    $(".wrap_share,.share_cover").removeClass("tab");
                }else{
                    $(".share_cover,.pay_container").removeClass("tab");
                }
            }
        }else{
            if(isWeiXin() == false){
                $(".wrap_share,.share_cover").removeClass("tab");
            }else{
                $(".share_cover,.pay_container").removeClass("tab");
            }
        }
        $('.share_cover').click(function(){
            $(".wrap_share,.share_cover").addClass("tab");
            $('body').css('overflow-y','scroll')
        })
        var config = {
                url:a_url,
                title:a_title,
                desc:a_desc,
                img:a_img,
                img_title:"",
                from:"火匣网",
                summary:a_summary
            };
        var share_obj = new nativeShare('nativeShare',config);
    });  

    if(isWeiXin() == false){
         $(".wrap_share .bottom").remove();
    }
    $('.pay_container,.share_cover').click(function(){
        $(".wrap_share,.share_cover,.pay_container").addClass("tab");
    })
    //判断是否是微信
    function isWeiXin(){
        var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            return true;
        }else{
            return false;
        }
    }
    // 点赞
    zan();
    function zan(){
        //商品点赞
        $('.click-praise>img').click(function(){
            $('.click-praise>i').html(parseInt($('.click-praise>i').text())+1);
            post({
                url:'/customizeProduct/'+_index+'/vote',
                success:function(data){
                    console.log(data)
                }
            })
        })
        //评论点赞
        $('.commentlist').delegate('.zan','click',function(){
            $(this).attr('src','img/zan-01.png')
        })
    }
    //评论大图
    imgBig();
    function imgBig(){
        $('.commentlist').delegate('.img_com','click',function(){
            $('.img_big').removeClass('tab').append('<img src="'+SERVER_CONTEXT_PATH +'/load/picture/'+$(this).data('img')+'" />')
            $('body').css('overflow-y','hidden')
        })
        $('.img_big,.img_grey').delegate('img', 'click', function() {
            $(this).remove();
            $('.img_big').addClass('tab');
            $('body').css('overflow-y','scroll')
        });
    }

})